package com.rtsapp.version.builder.utils;

import com.ksyun.ks3.dto.CannedAccessControlList;
import com.ksyun.ks3.exception.client.CallRemoteFailException;
import com.ksyun.ks3.exception.serviceside.NotFoundException;
import com.ksyun.ks3.http.HttpClientConfig;
import com.ksyun.ks3.service.Ks3;
import com.ksyun.ks3.service.Ks3Client;
import com.ksyun.ks3.service.Ks3ClientConfig;
import com.ksyun.ks3.service.request.HeadObjectRequest;
import com.ksyun.ks3.service.request.PutObjectRequest;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;


public class KS3PutUtil implements IPutFile {

    private final Ks3ClientConfig config = new Ks3ClientConfig();

    private Element ks3;

    private Element getRoot() {
        if (ks3 == null) {
            try {
                SAXReader saxReader = new SAXReader();
                Document dom = saxReader.read(new File("cfg/cdn.xml"));
                ks3 = dom.getRootElement().element("ks3");

                /**
                 * 设置服务地址</br>
                 * 中国（北京）| ks3-cn-beijing.ksyun.com
                 * 中国（上海）| ks3-cn-shanghai.ksyun.com
                 * 中国（香港）| ks3-cn-hk-1.ksyun.com
                 * 美国（圣克拉拉）| ks3-us-west-1.ksyun.com
                 */
                Element element = ks3.element("endpoint");
                String endpoint = "kss.ksyun.com";
                if (element != null) {
                    endpoint = element.attributeValue("value");
                }
                config.setEndpoint(endpoint);
                config.setProtocol(Ks3ClientConfig.PROTOCOL.http);
                /**
                 *true表示以   endpoint/{bucket}/{key}的方式访问</br>
                 *false表示以  {bucket}.endpoint/{key}的方式访问
                 */
                config.setPathStyleAccess(false);

                HttpClientConfig hconfig = new HttpClientConfig()
                        .withSocketTimeOut(100000)
                        .withConnectionTimeOut(20000)
                        .withMaxRetry(5);
                //在HttpClientConfig中可以设置httpclient的相关属性，比如代理，超时，重试等。

                config.setHttpClientConfig(hconfig);

            } catch (DocumentException e) {
                e.printStackTrace();
            }
        }
        return ks3;
    }

    private Ks3 getNewClient() {
        getRoot();

        Ks3 client = new Ks3Client(ks3.element("accessKeyID").attributeValue("value"), ks3.element("accessKeySecret").attributeValue("value"), config);

        return client;
    }

    public boolean putFiles(String keyPrefix, String pathPrefix, String path) {

        Ks3 client = getNewClient();
        HeadObjectRequest request = new HeadObjectRequest(ks3.element("bucketName").attributeValue("value"), keyPrefix + path);
        if (checkHasFile(client, request)) {
            return false;
        }

        client = getNewClient();
        PutObjectRequest uploadRequest = new PutObjectRequest(ks3.element("bucketName").attributeValue("value"), keyPrefix + path, new File(pathPrefix + path));
        //上传一个公开文件
        uploadRequest.setCannedAcl(CannedAccessControlList.PublicRead);
        CallRemoteFailException ex = null;
        client.putObject(uploadRequest);

        return true;

    }

    private boolean checkHasFile(Ks3 client, HeadObjectRequest request) {
        try {
            client.headObject(request);
            return true;
        } catch (NotFoundException e) {
            return false;
        }
    }
//
//    public void createPreload(String endpoint, String downloadSide, List<String> pathStrs, int maxVersionNo) throws Exception {
//
//        // 1. 设置ak sk
//        final String accessKey = ks3.element("accessKeyID").attributeValue("value");
//        final String secretKey = ks3.element("accessKeySecret").attributeValue("value");
//
//        AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
//        ClientConfiguration config = new ClientConfiguration();
//        config.setMaxErrorRetry(5);
//        AmazonCloudFrontClient client = new AmazonCloudFrontClient(credentials, config);
//        // 2. 设置 调用的地址
//        client.setEndpoint(endpoint);
//
//        // 1. 设置预加载的域名
//        String domain = downloadSide;
//        String distributionId = new String(Base64.encodeBase64(domain.getBytes("UTF-8")), "UTF-8");
//        System.out.println("distributionId: " + distributionId);
//
//        // 2. 设置预加载的路径
//        Paths paths = new Paths();
//        for (String pathStr : pathStrs) {
//            paths.withItems(pathStr);
//        }
//        paths.setQuantity(pathStrs.size());
//
//        String callerReference = String.valueOf(maxVersionNo) + String.valueOf(System.currentTimeMillis());
//
//        PreloadBatch batch = new PreloadBatch(paths, callerReference);
//        // 3. 创建预加载的请求
//        CreatePreloadRequest request = new CreatePreloadRequest(distributionId, batch);
//        // 4. 发送预加载的请求
//        CreatePreloadResult result = client.createPreload(request);
//        System.out.println(result.toString());
//    }

}
